package com.example.myapplication.model;

import android.os.AsyncTask;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class ChangePasswordTask extends AsyncTask<String, Void, String> {
    String phoneNumber;
    EditText editTextNewPassword;

    public ChangePasswordTask(String phoneNumber, EditText editTextNewPassword) {
        this.phoneNumber = phoneNumber;
        this.editTextNewPassword = editTextNewPassword;
    }

    @Override
    protected String doInBackground(String... params) {
        String urlString = params[0];
        String newPassword = editTextNewPassword.getText().toString();
        String result = "";

        try {
            String urlParameters = "phone_number=" + URLEncoder.encode(phoneNumber, "UTF-8") +
                    "&password=" + URLEncoder.encode(newPassword, "UTF-8");

            URL url = new URL(urlString + "?" + urlParameters);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            reader.close();
            result = sb.toString();

            urlConnection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            result = "Error: " + e.getMessage();
        }

        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            JSONObject jsonResult = new JSONObject(result);
            boolean success = jsonResult.getBoolean("success");
            if (success) {
                Toast.makeText(editTextNewPassword.getContext(), "修改成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(editTextNewPassword.getContext(), "与原密码相同", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(editTextNewPassword.getContext(), "服务器返回数据格式错误", Toast.LENGTH_SHORT).show();
        }
    }
}
